﻿using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.Reflection;
using System.IO;
using SneakyWeasel.Engine;

namespace SneakyWeasel
{
    class SWPluginKeyKill : SWPlugin
    {
        public Keys Key { get; set; }  // the key that will end the process tree

        public SWPluginKeyKill(Keys key)
        {
            this.Key = key;
        }

        public override void OnStart(ISWEngine sw, Form f)
        {
            f.KeyDown += new KeyEventHandler(this.KillKeyCheck);
        }

        public override void OnStop(ISWEngine sw, Form f)
        {
            f.KeyDown -= new KeyEventHandler(this.KillKeyCheck);
        }

        private void KillKeyCheck(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Key)
            {
                this.Engine.Stop(); // notify shut down
                KillAllProcesses();
            }
        }

        private void KillAllProcesses()
        {
            string procName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location);
            KillTask(procName);
            KillTask(procName + ".vshost"); // for Visual Studio
        }

        private void KillTask(string task)
        {
            System.Console.WriteLine("taskkill /f /im " + task + ".exe");
            ExecuteDosCommand("taskkill /f /im " + task + ".exe");
        }

        public static int ExecuteDosCommand(string command)
        {
            Process p;
            ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", "/C " + command);
            psi.CreateNoWindow = false;
            psi.UseShellExecute = false;
            p = Process.Start(psi);

            p.WaitForExit();
            int exitCode = p.ExitCode;
            p.Close();

            return exitCode;
        }
    }
}
